import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/components/Layout/index.vue'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import Blockchain from '@/views/admin/Blockchain.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
  },
  {
    path: '/',
    component: Layout,
    redirect: '/attendance/face',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
      },
      {
        path: 'attendance',
        name: 'Attendance',
        component: () => import('@/views/attendance/index.vue'),
        children: [
          {
            path: 'face',
            name: 'AttendanceFace',
            component: () => import('@/views/attendance/Face.vue'),
          },
        ],
      },
      {
        path: 'employee',
        name: 'Employee',
        component: () => import('@/views/employee/index.vue'),
        children: [
          {
            path: 'info',
            name: 'EmployeeInfo',
            component: () => import('@/views/employee/Info.vue'),
          },
          {
            path: 'statistics',
            name: 'EmployeeStatistics',
            component: () => import('@/views/employee/Statistics.vue'),
          },
          {
            path: 'record',
            name: 'EmployeeRecord',
            component: () => import('@/views/employee/Record.vue'),
          },
          {
            path: 'apply',
            name: 'EmployeeApply',
            component: () => import('@/views/employee/Apply.vue'),
          },
          
          {
            path: 'exception',
            name: 'EmployeeException',
            component: () => import('@/views/employee/Exception.vue'),
          },
        ],
      },
      {
        path: 'admin',
        name: 'Admin',
        component: () => import('@/views/admin/index.vue'),
        meta: { requiresAdmin: true },
        children: [
          {
            path: 'dashboard',
            name: 'AdminDashboard',
            component: () => import('@/views/admin/Dashboard.vue'),
          },
          {
            path: 'manual-attendance',
            name: 'ManualAttendance',
            component: () => import('@/views/admin/ManualAttendance.vue'),
          },
          {
            path: 'employee-audit',
            name: 'EmployeeAudit',
            component: () => import('@/views/admin/EmployeeAudit.vue'),
          },
          {
            path: 'user-manage',
            name: 'UserManage',
            component: () => import('@/views/admin/UserManage.vue'),
          },
          {
            path: 'list',
            name: 'EmployeeList',
            component: () => import('@/views/admin/List.vue'),
          },
          {
            path: 'department',
            name: 'Department',
            component: () => import('@/views/admin/Department.vue'),
          },
          {
            path: 'announcement',
            name: 'Announcement',
            component: () => import('@/views/admin/Announcement.vue'),
          },
          {
            path: 'apply',
            name: 'AdminApply',
            component: () => import('@/views/admin/Apply.vue'),
            meta: { title: '请假审批', icon: 'Calendar' }
          },
          {
            path: 'blockchain',
            name: 'Blockchain',
            component: Blockchain,
            meta: { title: '区块链信息', icon: 'Link' }
          }
        ],
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 修改路由守卫,使用Pinia状态判断管理员权限
router.beforeEach((to, from, next) => {
  // 不需要登录就可以访问的路由
  const publicPages = ['/attendance/face', '/login', '/register']
  const authRequired = !publicPages.includes(to.path)
  const isLoggedIn = localStorage.getItem('token')

  if (authRequired && !isLoggedIn) {
    next('/login')
  } else if (to.matched.some((record) => record.meta.requiresAdmin)) {
    // 使用Pinia获取用户状态，如果Pinia中没有则从localStorage获取
    const userStore = useUserStore()
    const isAdmin = userStore.isAdmin || localStorage.getItem('isAdmin') === 'true'
    
    // 如果从localStorage中获取到了管理员状态，同步到Pinia中
    if (!userStore.isAdmin && localStorage.getItem('isAdmin') === 'true') {
      userStore.setUser({
        isAdmin: true,
        ...JSON.parse(localStorage.getItem('userInfo') || '{}')
      })
    }

    if (!isAdmin) {
      ElMessage.warning('您没有管理员权限，无法访问此页面')
      next('/')
      return
    }
    next()
  } else {
    next()
  }
})

export default router
